<template>
  <a-card :bordered="false">
    <h2>代价因子权重设置（权重相加必须为100）</h2>
    <a-form
      :form="form"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 6 }"
      @submit="handleSubmit"
    >
    <a-row>
      <a-col :span="16">
        <a-form-item
          v-for="d in factors"
          v-show="d.enabled"
          :key="d.id"
          :label="d.factorName"
        >
          <a-input
            autocomplete="off"
            style="width: 125px"
            addon-after="%"
            @keyup="clearNoNum(d.id)"
            v-decorator="[
              d.id,
              {
                initialValue: d.weight,
                rules: [
                  {
                    validator: weightValidator,
                  },
                  { required: true, message: '请输入' + d.factorName + '权重' },
                  { validator: validators.xmax({max:100}), trigger: 'change', },
                  { validator: validators.xmin({min:0}), trigger: 'change', },
                ],
              }
            ]"
            @blur="(e) => onWeightBlur(d.id)"
          />
          <!-- <a-input-number
            style="width: 180px;"
            :min="0"
            :max="100"
            :parser="value => value ? (isNaN(value) ? 0 : parseInt(value)) : 0"
            @blur="() => onWeightBlur()"
            v-decorator="[
              d.id,
              {
                initialValue: d.weight,
                rules: [
                  {
                    required: true,
                    message: '请输入' + d.factorName + '权重',
                  },
                  {
                    validator: weightValidator,
                  }
                ],
              },
            ]"
          />
          <div
            class="rule-unit"
          >
            %
          </div> -->
          <!-- <span style="display: inline-block;padding-left: 10px">%</span> -->
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 3 }">
          <a-button
            :disabled="factors.length === 0"
            type="primary"
            html-type="submit"
          > 提交 </a-button>
        </a-form-item>
      </a-col>
    </a-row>
    </a-form>
  </a-card>
</template>

<script>
  import { gPostAction } from "@/api/manage";
  import { filterNoNum } from "@/utils/util";

  export default {
    name: "Weight",
    data() {
      return {
        formLayout: "horizontal",
        form: this.$form.createForm(this, { name: "coordinated" }),
        factors: [],
      };
    },
    mounted() {
      this.loadData();
    },
    methods: {
      clearNoNum(fieldName) {
        let obj = {};
        obj[fieldName] = filterNoNum(this.form.getFieldValue(fieldName));
        this.form.setFieldsValue(obj);
        this.form.validateFields([fieldName], (errors, values) => {});
      },
      loadData() {
        gPostAction("/model/getModelFactors", { modelType: "COST", title: "离线业务多数据中心迁移-离线业务异步迁移代价-代价展示​-异步迁移代价因子权重设置", content: "查看异步迁移代价因子权重" }).then((res) => {
          if (res.success) {
            this.factors = res.data
          }
        })
      },
      weightValidator(rule, value, callback) {
        let total = 0
        this.factors.filter(item => item.enabled === true).map(item => item.id).forEach(item => {
          total += parseInt(this.form.getFieldValue(item))
        })
        if (total !== 100) {
          callback('所有的因子权重相加必须等于100%')
        }
        callback()
      },
      onWeightBlur(fieldName) {
        if (fieldName) {
          this.clearNoNum(fieldName);
        }
        this.form.validateFields()
      },
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            const postData = {};
            postData.modelType = "COST";
            postData.title = "离线业务多数据中心迁移-离线业务异步迁移代价-代价展示-异步迁移代价因子权重设置";
            postData.content = "异步迁移代价因子权重设置";
            this.factors.forEach((item, i) => {
              postData['factors[' + i + '].id'] = item.id;
              postData['factors[' + i + '].weight'] = values[item.id];
              postData['factors[' + i + '].scoreType'] = item.scoreType;
              postData['factors[' + i + '].scoreSample'] = item.scoreSample;
              postData['factors[' + i + '].factorName'] = item.factorName;
              postData['factors[' + i + '].enabled'] = item.enabled;
            });
            gPostAction("/model/setModelFactors", postData).then((res) => {
              if (res.success) {
                this.$message.success("操作成功");
              }
            });
          }
        });
      },
    },
  };
</script>
